package com.desaysv.someip;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.Nullable;

/**
 * @author linzi
 * @date 2023-3-7
 */
public class SomeIpService extends Service {
    private static final String TAG = "[SomeIpService]";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    private ISomeIpCallback someIpCallback;
    private ISomeIpService.Stub binder = new ISomeIpService.Stub() {
        @Override
        public void register(ISomeIpCallback callback) throws RemoteException {
            someIpCallback = callback;
        }

        @Override
        public void send(int methodId, byte[] payload) throws RemoteException {
            Log.e(TAG, "send: " + methodId);
            SomeIpManager.getInstance().send(methodId, payload);
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate: ");
        SomeIpManager.getInstance().removeObserver(someIpObserver);
        SomeIpManager.getInstance().addObserver(someIpObserver);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        SomeIpManager.getInstance().destroy();
    }

    SomeIpManager.SomeIpObserverImpl someIpObserver = new SomeIpManager.SomeIpObserverImpl() {
        @Override
        public void response(SomeIpMessager messager) {
            if (someIpCallback == null) {
                return;
            }
            try {
                someIpCallback.response(messager);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void timeout(int methodId, int sessionId) {
            if (someIpCallback == null) {
                return;
            }
            try {
                someIpCallback.timeout(methodId, sessionId);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    };
}
